<template>
  <div class="course-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.cname" placeholder="课程关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.tname" placeholder="老师关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.department" placeholder="系关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
  <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="tableLoading"
        border
        style="width: 100%"
        size="small"
      >
  <el-table-column type="index" label="序号" width="60" align="center" />
  <el-table-column prop="course_name" label="课程名" show-overflow-tooltip />
  <el-table-column prop="teacher_name" label="代课教师" width="100" />
  <el-table-column prop="department_name" label="所属系" show-overflow-tooltip />
  <el-table-column prop="course_grade" label="年级" width="70" align="center" />
  <el-table-column prop="course_credit" label="学分" width="70" align="center">
    <template #default="{ row }">
      <span class="badge badge--blue">{{ row.course_credit }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="course_time" label="上课时间" :formatter="formatterTime" show-overflow-tooltip />
  <el-table-column prop="course_selected_count" label="已选" width="70" align="center">
    <template #default="{ row }">
      <span class="badge badge--green">{{ row.course_selected_count }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="course_max_size" label="座位数" width="80" align="center">
    <template #default="{ row }">
      <span class="badge badge--gray">{{ row.course_max_size }}</span>
    </template>
  </el-table-column>
  <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <div style="display: flex; justify-content: space-around">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        size="small"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" class="form-dialog" modal-class="light-modal-mask">
      <el-form
        :model="dialogForm"
        :rules="courseRules"
        ref="formRef"
        label-width="120px"
        size="small"
      >
        <el-form-item label="课程名称" prop="course_name">
          <el-input v-model="dialogForm.course_name"></el-input>
        </el-form-item>
        <el-form-item label="课程年级" prop="course_grade">
          <el-input v-model="dialogForm.course_grade"></el-input>
        </el-form-item>
        <el-form-item label="上课时间" prop="course_time">
          <div class="inline">
            <el-select v-model="courseTime.week" placeholder="星期">
              <el-option v-for="(w, i) in weeks" :key="i" :value="i" :label="w"></el-option>
            </el-select>
            <el-select v-model="courseTime.start" placeholder="开始节数">
              <el-option v-for="c in 10" :key="c" :value="c - 1" :label="`第${c}节`"></el-option>
            </el-select>
            <el-select v-model="courseTime.end" placeholder="持续节数">
              <el-option v-for="c in 4" :key="c" :value="c" :label="`共${c}节`"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="上课地点" prop="course_location">
          <el-input v-model="dialogForm.course_location"></el-input>
        </el-form-item>
        <el-form-item label="学分" prop="course_credit">
          <el-input v-model="dialogForm.course_credit"></el-input>
        </el-form-item>
        <el-form-item label="最大人数" prop="course_max_size">
          <el-input v-model="dialogForm.course_max_size"></el-input>
        </el-form-item>
        <el-form-item label="考试时间" prop="course_exam_date">
          <el-date-picker
            v-model="dialogForm.course_exam_date"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="考试地点" prop="course_exam_location">
          <el-input v-model="dialogForm.course_exam_location"></el-input>
        </el-form-item>
        <el-form-item label="授课老师" prop="course_teacher_id">
          <el-select
            v-model="dialogForm.course_teacher_id"
            filterable
            remote
            :remote-method="remoteMethod"
            placeholder="请选择老师"
          >
            <el-option
              v-for="item in teacherList"
              :key="item.teacher_id"
              :label="item.teacher_name"
              :value="item.teacher_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <BaseConfirmDialog
      :visible="confirmVisible"
      title="提示"
      :message="confirmMessage"
      confirm-text="确定"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="confirmVisible=false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  getCourseAPI,
  addCourseAPI,
  updateCourseAPI,
  deleteCourseAPI
} from '@/api/admin/course.js'
import { getTeacherAPI } from '@/api/admin/teacher.js'
import BaseConfirmDialog from '@/components/BaseConfirmDialog.vue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { weeks } from '@/constant'
import courseRules from '@/rules/courseRules'

// 搜索表单
const searchForm = reactive({
  cname: '',
  tname: '',
  department: ''
})

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const dialogForm = reactive({
  course_id: '',
  course_teacher_id: '',
  course_name: '',
  course_grade: '',
  course_time: '',
  course_location: '',
  course_credit: '',
  course_max_size: '',
  course_exam_date: '',
  course_exam_location: ''
})
const isEdit = ref(false)

const courseTime = reactive({
  week: '',
  start: '',
  end: ''
})

watch(courseTime, (newVal) => {
  if (newVal.week !== '' && newVal.start !== '' && newVal.end !== '') {
    dialogForm.course_time = `${newVal.week}-${newVal.start}-${newVal.end}`
  }
})

// 老师下拉列表
const teacherList = ref([])

// 获取课程数据
const fetchCourses = async () => {
  const params = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    ...searchForm
  }
  tableLoading.value = true
  try {
    const res = await getCourseAPI(params)
    // 拦截器已返回 data
    tableData.value = res?.list || []
    pagination.total = res?.total || 0
  } finally {
    tableLoading.value = false
  }
}

// 获取老师数据
const fetchTeachers = async (tname = '') => {
  const res = await getTeacherAPI({ pageNo: 1, pageSize: 999, tname })
  teacherList.value = res?.list || []
}

const remoteMethod = (query) => {
  if (query) {
    fetchTeachers(query)
  } else {
    teacherList.value = []
  }
}

onMounted(() => {
  fetchCourses()
  fetchTeachers()
})

// 格式化上课时间
const formatterTime = (row, column, cellValue) => {
  if (!cellValue) return ''
  const [w, s, e] = cellValue.split('-')
  return `${weeks[w]} 第${parseInt(s) + 1}至${parseInt(s) + parseInt(e)}节`
}

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1
  fetchCourses()
}

// 重置
const handleReset = () => {
  searchForm.cname = ''
  searchForm.tname = ''
  searchForm.department = ''
  pagination.pageNo = 1
  fetchCourses()
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加课程'
  Object.assign(dialogForm, {
    course_id: '',
    course_teacher_id: '',
    course_name: '',
    course_grade: '',
    course_time: '',
    course_location: '',
    course_credit: '',
    course_max_size: '',
    course_exam_date: '',
    course_exam_location: ''
  })
  Object.assign(courseTime, { week: '', start: '', end: '' })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑课程'
  Object.assign(dialogForm, row)
  if (row.course_time) {
    const [w, s, e] = row.course_time.split('-')
    Object.assign(courseTime, { week: parseInt(w), start: parseInt(s), end: parseInt(e) })
  }
  dialogVisible.value = true
}

// 删除
const confirmVisible = ref(false)
const confirmMessage = ref('')
let pendingDeleteId = ''
const handleDelete = (row) => {
  pendingDeleteId = row.course_id
  confirmMessage.value = `确定要删除课程 "${row.course_name}" 吗？`
  confirmVisible.value = true
}
const confirmDelete = async () => {
  await deleteCourseAPI({ course_id: pendingDeleteId })
  confirmVisible.value = false
  fetchCourses()
}

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate()
  let res
  if (isEdit.value) {
    res = await updateCourseAPI(dialogForm)
  } else {
    res = await addCourseAPI(dialogForm)
  }
  // 成功消息已由响应拦截器统一处理
  dialogVisible.value = false
  fetchCourses()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchCourses()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchCourses()
}
</script>

<style lang="scss" scoped>
.course-container {
  padding: 8px 20px 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.search-bar {
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0 0 18px 0;
  background: none;
  border: none;
  box-shadow: none;
}
.search-form {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 0;
  margin: 0;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 8px;
}
.search-form .el-input__wrapper,
.search-form .el-button {
  height: 26px !important;
  min-height: 26px !important;
  font-size: 13px;
}
.table-card {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding-top: 6px;
}
.table-card :deep(.el-card__body) {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.table-card :deep(.el-table) {
  flex: 1 1 auto;
  /* 禁止外层产生横向滚动，避免左右拖动 */
  overflow-x: hidden;
  overflow-y: auto;
}
.pagination {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
.inline {
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  gap: 10px;
}
.inline .el-select {
  flex-grow: 1;
}
:deep(.el-date-editor) {
  width: 100%;
}
</style>


